<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { BorderBox12 as DvBorderBox12, BorderBox7 as DvBorderBox7, BorderBox2 as DvBorderBox2, Decoration5 as DvDecoration5, BorderBox8 as DvBorderBox8, Decoration6 as DvDecoration6 } from '@kjgl77/datav-vue3'
import TopPanel from '@/components/IndexComponents/TopPanel.vue'
import { NCarousel } from 'naive-ui/lib/carousel'
import TrendChart from '@/components/common/TrendChart.vue'
import NpkBarChart from '@/components/common/NpkBarChart.vue'
import SoilDataPieChart from '@/components/common/SoilDataPieChart.vue'
import VegetablePriceChart from '@/components/common/VegetablePriceChart.vue'
import { useSensorStore } from '@/stores/sensor'

// 定义接口返回数据的类型
interface SensorData {
  id: string
  name: string
  value: number
  timestamp: string
}

interface CaptureData {
  picUrl: string
  captureTime: string
  quality: number
  sensorData: SensorData[]
}

interface CaptureRecord {
  code: string
  msg: string
  data: CaptureData
}

interface ApiResponse {
  code: number
  message: string
  data: CaptureRecord[]
}

const router = useRouter()

// 修改照片数据的类型和初始化
const photos = ref<CaptureData[]>([])
const loading = ref(false)
const error = ref<string | null>(null)

// 修改获取图片URL的函数
const getImageUrlWithToken = (url: string): string => {
  const token = localStorage.getItem('token')
  if (!token) {
    console.error('未登录或token已失效')
    return url
  }
  
  try {
    // 移除旧的token参数（如果有的话）
    const urlObj = new URL(url)
    urlObj.searchParams.delete('token')
    // 添加新的token
    urlObj.searchParams.append('token', token)
    return urlObj.toString()
  } catch (err) {
    console.error('URL处理失败:', err)
    return url
  }
}

// 添加图片错误处理
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  const token = localStorage.getItem('token')
  
  if (!token) {
    console.error('未登录或token已失效')
    error.value = '登录已过期，请重新登录'
    router.push('/login')
    return
  }

  // 尝试重新加载图片
  const originalUrl = img.src.split('?')[0]
  img.src = getImageUrlWithToken(originalUrl)
}

// 修改获取照片数据的函数
const fetchPhotos = async () => {
  loading.value = true
  error.value = null
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      throw new Error('未登录，请先登录')
    }

    const response = await fetch('/api/camera/captures/week', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      cache: 'no-cache'
    })
    
    if (!response.ok) {
      if (response.status === 401 || response.status === 403) {
        localStorage.removeItem('token')
        localStorage.removeItem('isLogin')
        router.push('/login')
        throw new Error('登录已过期，请重新登录')
      } else if (response.status === 404) {
        throw new Error('API 接口不存在，请检查后端服务是否正常运行')
      } else {
        throw new Error(`请求失败: ${response.status}`)
      }
    }
    
    const contentType = response.headers.get("content-type")
    if (!contentType || !contentType.includes("application/json")) {
      console.error('响应头:', response.headers)
      throw new TypeError("返回的数据不是JSON格式")
    }

    const result: ApiResponse = await response.json()
    console.log('API返回的原始数据:', result)

    if (result.code === 200 && result.data) {
      photos.value = result.data
        .filter(record => record.code === '200')
        .map(record => record.data)
      console.log('处理后的照片数据:', photos.value)
      currentPhotoIndex.value = 0
    } else {
      throw new Error(result.message || '获取照片失败')
    }
  } catch (e) {
    error.value = e instanceof Error ? e.message : '网络请求失败'
    console.error('获取照片数据失败:', e)
    photos.value = []
  } finally {
    loading.value = false
  }
}

// 添加刷新功能
const refreshPhotos = async () => {
  await fetchPhotos()
  // 只获取历史数据
  if (sensorStore) {
    await sensorStore.fetchWeekData()
  }
}

// 添加 sensorStore
const sensorStore = useSensorStore()

onMounted(() => {
  fetchPhotos()
})

// 格式化图片数据，添加传感器数据显示
const imageData = computed(() => {
  return photos.value.map(photo => ({
    url: getImageUrlWithToken(photo.picUrl),
    captureTime: new Date(photo.captureTime).toLocaleString(),
    sensorData: photo.sensorData
  }))
})

// 添加当前选中照片索引
const currentPhotoIndex = ref(0)

// 添加处理照片切换的函数
const handlePhotoChange = (index: number) => {
  currentPhotoIndex.value = index
}

// 计算当前选中照片的传感器数据
const currentSensorData = computed(() => {
  if (!photos.value.length || currentPhotoIndex.value >= photos.value.length) {
    console.log('没有照片数据或索引超出范围')
    return null
  }
  const data = photos.value[currentPhotoIndex.value].sensorData
  console.log('当前选中照片的传感器数据:', data)
  return data
})

// 更新土壤监测数据显示
const soilData = computed(() => {
  if (!currentSensorData.value) {
    console.log('没有传感器数据，显示默认值')
    return [
      { value: '--', unit: 'MG/KG', label: '土壤含氮量', status: '--' },
      { value: '--', unit: 'MG/KG', label: '土壤含磷量', status: '--' },
      { value: '--', unit: 'MG/KG', label: '土壤含钾量', status: '--' }
    ]
  }

  console.log('开始处理土壤数据')
  const findSensorValue = (name: string) => {
    const sensorData = currentSensorData.value
    if (!sensorData) return { value: '--', status: '--' }
    
    const sensor = sensorData.find(s => s.name.includes(name))
    console.log(`查找${name}:`, sensor)
    return sensor ? {
      value: sensor.value.toString(),
      status: getSoilStatus(name, sensor.value)
    } : { value: '--', status: '--' }
  }

  const nitrogenData = findSensorValue('氮')
  const phosphorusData = findSensorValue('磷')
  const potassiumData = findSensorValue('钾')

  console.log('处理后的土壤数据:', {
    nitrogen: nitrogenData,
    phosphorus: phosphorusData,
    potassium: potassiumData
  })

  return [
    { value: nitrogenData.value, unit: 'MG/KG', label: '土壤含氮量', status: nitrogenData.status },
    { value: phosphorusData.value, unit: 'MG/KG', label: '土壤含磷量', status: phosphorusData.status },
    { value: potassiumData.value, unit: 'MG/KG', label: '土壤含钾量', status: potassiumData.status }
  ]
})

// 获取土壤状态
const getSoilStatus = (name: string, value: number) => {
  const standards: Record<string, [number, number]> = {
    '氮': [3, 8],
    '磷': [5, 10],
    '钾': [15, 20]
  }

  const [min, max] = standards[name] || [0, 0]
  if (value < min) return '低'
  if (value > max) return '高'
  return '良'
}

// 传递给各个图表组件的数据
const chartProps = computed(() => {
  return {
    sensorData: currentSensorData.value || [],
    timestamp: photos.value[currentPhotoIndex.value]?.captureTime || ''
  }
})

// 添加返回主页函数
const goToHome = () => {
  router.push('/')
}

// 传递给 TopPanel 的属性
const topPanelProps = {
  overrideDataTraceText: '主页面', // 覆盖数据回溯按钮的文字
  onDataTraceClick: goToHome, // 使用返回主页的函数
  overrideRefreshFunction: refreshPhotos, // 覆盖刷新功能
  overrideRefreshText: '获取历史照片' // 覆盖刷新按钮的文字
}
</script>

<template>
  <div class="data-trace">
    <TopPanel v-bind="topPanelProps" />
    <div class="content-wrapper">
      <!-- 左侧照片轮播 -->
      <div class="left-panel">
        <DvBorderBox13 class="photo-box">
          <div class="photo-content">
            <div class="info-grid">
              <dv-border-box12 class="info-border">
                <div class="info-item">
                  <span class="label">智慧大棚编号</span>
                  <span class="value">F-02</span>
                </div>
              </dv-border-box12>
              <dv-border-box12 class="info-border">
                <div class="info-item">
                  <span class="label">占地面积</span>
                  <span class="value">5.65 亩</span>
                </div>
              </dv-border-box12>
              <dv-border-box12 class="info-border">
                <div class="info-item">
                  <span class="label">生长阶段</span>
                  <span class="value">开花结果期</span>
                </div>
              </dv-border-box12>
            </div>
            
            <!-- 添加土壤监测数据 -->
            <div class="soil-grid">
              <DvBorderBox8 :dur="5" v-for="(item, index) in soilData" :key="index" class="soil-box">
                <div class="soil-content">
                  <div class="soil-main">
                    <span class="soil-value">{{ item.value }}</span>
                    <span class="soil-unit">{{ item.unit }}</span>
                    <span class="soil-status">{{ item.status }}</span>
                  </div>
                  <div class="soil-label">{{ item.label }}</div>
                </div>
              </DvBorderBox8>
            </div>
            
            <div class="carousel-container">
              <dv-border-box12>
                <div class="header">
                  <dv-decoration3 class="decoration" />
                  <div class="title-container">
                    <h3 class="title">照片记录</h3>
                  </div>
                  <dv-decoration3 class="decoration" />
                </div>
                <n-carousel
                  v-if="photos.length > 0"
                  show-arrow
                  :autoplay="false"
                  class="carousel-content"
                  @update:current-index="handlePhotoChange"
                >
                  <div
                    v-for="(item, index) in imageData"
                    :key="item.url"
                    class="carousel-item"
                  >
                    <img
                      :src="item.url"
                      class="carousel-image"
                      alt="大棚照片"
                      @error="handleImageError"
                    >
                    <div class="photo-info">
                      <div class="capture-time">拍摄时间：{{ item.captureTime }}</div>
                    </div>
                  </div>
                </n-carousel>
                <div v-else-if="loading" class="loading-state">
                  正在加载照片数据...
                </div>
                <div v-else-if="error" class="error-state">
                  {{ error }}
                </div>
                <div v-else class="no-photos">
                  暂无历史照片
                </div>
              </dv-border-box12>
            </div>
          </div>
        </DvBorderBox13>
      </div>

      <!-- 右侧内容 -->
      <div class="right-panel">
        <DvBorderBox13 class="photo-box">
          <div class="chart-wrapper">
            <div class="chart-column">
              <!-- 土壤数据饼图 -->
              <dv-border-box8 :reverse="true" class="pie-box">
                <div class="chart-title">
                  <dv-decoration6 class="title-decoration" />
                  <h3>土壤数据分析</h3>
                  <dv-decoration6 class="title-decoration" />
                </div>
                <div class="chart-content">
                  <SoilDataPieChart v-bind="chartProps" />
                </div>
              </dv-border-box8>
              
              <!-- 菜价分析 -->
              <dv-border-box8 :reverse="true" class="price-box">
                <div class="chart-title">
                  <dv-decoration6 class="title-decoration" />
                  <h3>菜价分析</h3>
                  <dv-decoration6 class="title-decoration" />
                </div>
                <div class="chart-content">
                  <VegetablePriceChart />
                </div>
              </dv-border-box8>
            </div>
            
            <div class="chart-column">
              <div class="chart-container">
                <!-- 温度趋势图 -->
                <dv-border-box8 :reverse="true" class="trend-box">
                  <div class="chart-title">
                    <dv-decoration6 class="title-decoration" />
                    <h3>温度检测数据统计</h3>
                    <dv-decoration6 class="title-decoration" />
                  </div>
                  <div class="chart-content">
                    <TrendChart />
                  </div>
                </dv-border-box8>
                
                <!-- 氮磷钾含量柱状图 -->
                <dv-border-box8 :reverse="true" class="npk-box">
                  <div class="chart-title">
                    <dv-decoration6 class="title-decoration" />
                    <h3>氮磷钾含量统计</h3>
                    <dv-decoration6 class="title-decoration" />
                  </div>
                  <div class="chart-content">
                    <NpkBarChart v-bind="chartProps" />
                  </div>
                </dv-border-box8>
              </div>
            </div>
          </div>
        </DvBorderBox13>
      </div>
    </div>
  </div>
</template>

<style scoped>
.data-trace {
  width: 2560px;
  height: 1440px;
  background: #001529;
  display: flex;
  flex-direction: column;
}

.content-wrapper {
  width: 2560px;
  height: 1200px;
  gap: 20px;
  padding: 20px;
  margin: 0 auto;
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
}

.left-panel {
  width: 1120px;
  height: 1150px;
}

.photo-box {
  width: 100%;
  height: 100%;
  background: rgba(0, 24, 48, 0.6);
}

.photo-content {
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 16px;
}

.header .decoration {
  width: 450px;
  height: 30px;
}

.header .title {
  color: #d9faff;
  font-size: 24px;
  font-weight: bold;
}

.section-title {
  color: #d9faff;
  font-size: 24px;
  text-align: center;
  margin-bottom: 20px;
}

.carousel-container {
  position: relative;
  width: 1100px;
  height: 900px;
  overflow: hidden;
  padding: 20px;
}

.carousel-title {
  color: #d9faff;
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  padding-top: 20px;
}

.decoration {
  width: 160px;
  height: 20px;
}

.carousel-image {
  width: 1030px;
  height: 780px;
  border-radius: 20px;
}


.no-photos {
  color: #4fd2dd;
  font-size: 20px;
  text-align: center;
  height: 800px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.right-panel {
  width: 1400px;
  height: 1150px;
  display: flex;
  justify-content: flex-end;
}

/* 添加顶部导航样式 */
.top-panel {
  width: 2560px;
  height: 100px;
  position: relative;
  background-color: rgba(0, 24, 48, 0.6);
}

.left-section {
  display: flex;
  gap: 80px;
}

.button-box {
  width: 160px;
  height: 50px;
}

.nav-button {
  width: 100%;
  height: 100%;
  font-size: 22px;
  color: #d9faff;
  background: transparent;
  border: none;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  margin: 0;
  outline: none;
}

.nav-button:hover {
  color: #64ffda;
}

/* Naive UI 轮播图式 */
:deep(.n-carousel) {
  height: 100%;
  background: transparent;
}


:deep(.n-carousel__dots) {
  background: transparent;
  padding: 8px;
  margin-bottom: 20px;
}

:deep(.n-carousel__dot) {
  background-color: rgba(255, 255, 255, 0.4);
}

:deep(.n-carousel__dot--active) {
  background-color: #fff;
}

:deep(.n-carousel__arrow) {
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 50%;
  color: #fff;
  width: 40px;
  height: 40px;
}

:deep(.n-carousel__arrow:hover) {
  background-color: rgba(0, 0, 0, 0.6);
}

:deep(.n-carousel__dots) {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 10;
}

:deep(.n-carousel__arrow--left) {
  font-size: 40px;
  margin-right: 30px;
  font-weight: bold;
}

:deep(.n-carousel__arrow--right) {
  font-size: 40px;
  margin-right: 30px;
  font-weight: bold;
}

.carousel-content {
  width: 1030px;
  height: 780px;
  position: relative;
  background: transparent;
  object-fit: contain;
  margin-left: 15px
}

.info-grid {
  height: 80px;
  width: 100%;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  padding: 0 15px;
  margin-bottom: 20px;
}

.info-border {
  height: 80px;
  width: 100%;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-radius: 8px;
  height: 60px;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

.label {
  color: #ffc93c;
  font-size: 18px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.value {
  font-size: 22px;
  color: #d9faff;
  display: flex;
  align-items: center;
}

/* 添加土壤监测数据样式 */
.soil-grid {
  height: 100px;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  padding: 0 20px;
  margin-bottom: 20px;
}

.soil-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
}

.soil-main {
  display: flex;
  align-items: baseline;
  gap: 8px;
  padding: 5px 20px;
  justify-content: center;
}

.soil-value {
  color: #d9faff;
  font-size: 32px;
  text-align: center;
}

.soil-unit {
  color: #4fd2dd;
  font-size: 14px;
  text-align: center;
}

.soil-status {
  color: #4fd2dd;
  font-size: 14px;
  background-color: #004a7c;
  border-radius: 5px;
  padding: 0 5px;
  text-align: center;
}

.soil-label {
  color: #ffc93c;
  font-size: 16px;
  text-align: center;
  font-weight: bold;
  margin-bottom: 10px;
}

.chart-wrapper {
  display: flex;
  width: 100%;
  height: 100%;
  gap: 20px;
}

.chart-column {
  width: 50%;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.pie-box {
  width: 100%;
  height: 500px;
  margin-top: 20px;
}

.price-box {
  width: 100%;
  height: 500px;
}

.chart-container {
  padding: 20px;
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.trend-box {
  width: 100%;
  height: 500px;
}

.chart-title {
  display: flex;  
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding-top: 20px;
}

.title-decoration {
  width: 190px;
  height: 40px;
}

.chart-title h3 {
  color: #d9faff;
  margin: 0;
  font-size: 25px;
  text-align: center;
  font-weight: bold;
}

.chart-content {
  width: 100%;
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.npk-box {
  width: 100%;
  height: 500px;
}

.carousel-item {
  position: relative;
  width: 100%;
  height: 100%;
}

.photo-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  color: #fff;
  padding: 15px;
}

.capture-time {
  font-size: 16px;
  margin-bottom: 10px;
  color: #4fd2dd;
}

.sensor-data {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}

.sensor-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.sensor-name {
  color: #ffc93c;
  font-size: 14px;
}

.sensor-value {
  color: #d9faff;
  font-size: 14px;
}

.loading-state,
.error-state {
  color: #4fd2dd;
  font-size: 20px;
  text-align: center;
  height: 800px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.error-state {
  color: #ff4d4f;
}

.title-container {
  display: flex;
  align-items: center;
  gap: 15px;
}

/* 移除不再需要的样式 */
.refresh-btn {
  display: none;
}
.refresh-btn:hover:not(:disabled) {
  display: none;
}
.refresh-btn:disabled {
  display: none;
}
.fa-spin {
  display: none;
}
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

</style>
